package com.sywb.chuangyebao.view.dialog;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.DistrictInfo;
import com.sywb.chuangyebao.bean.InterestIndustryInfo;

import org.bining.footstone.db.DbManager;
import org.bining.footstone.db.assit.QueryBuilder;
import org.bining.footstone.log.Logger;
import org.bining.footstone.widget.WheelView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class WheelViewDialog extends BaseDialogFragment {

    @BindView(R.id.wheelview_left)
    WheelView mWheelLeft;
    @BindView(R.id.wheelview_center)
    WheelView mWheelCenter;
    @BindView(R.id.wheelview_right)
    WheelView mWheelRight;

    private int mType;
    private Calendar calendar;

    private List<DistrictInfo> provinceList;
    private List<DistrictInfo> areaList;

    private List<Integer> industryIdList;

    private SelectedCompleteListener mCompleteListener;

    public static WheelViewDialog newInstance(Object... pramars) {
        WheelViewDialog dialogFragment = new WheelViewDialog();
        Bundle bundle = new Bundle();
        if (pramars != null && pramars.length > 0) {
            for (int i = 0; i < pramars.length; i++) {
                bundle.putSerializable("p" + i, (Serializable) pramars[i]);
            }
        }
        dialogFragment.setArguments(bundle);
        return dialogFragment;
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.dialog_wheelview;
    }

    @Override
    public void initView(View view, Bundle bundle) {
        if (bundle != null) {
            mType = bundle.getInt("p0", 1);
        } else {
            mType = getArguments().getInt("p0", 1);
        }

        mWheelLeft.setLineHeight(1);
        mWheelCenter.setLineHeight(1);
        mWheelRight.setLineHeight(1);

        switch (mType) {
            case 1:
                int selectSex = getArguments().getInt("p1", 0);
                initSexData(selectSex);
                break;
            case 2:
                int year = getArguments().getInt("p1", 0);
                int month = getArguments().getInt("p2", 0);
                int day = getArguments().getInt("p3", 0);
                initAgeData(year, month, day);
                break;
            case 3:
                String areaId = getArguments().getString("p1", null);
                initAreaData(areaId);
                break;
            case 4:
                int selectPeriod = getArguments().getInt("p1", 0);
                initPeriodData(selectPeriod);
                break;
            case 5:
                int industry = getArguments().getInt("p1", 0);
                initIndustryData(industry);
                break;
            case 6:
                int investmentBudget = getArguments().getInt("p1", 0);
                initInvestmentBudget(investmentBudget);
                break;
        }
    }

    @OnClick({R.id.tv_complete, R.id.tv_cancel, R.id.rl_wheel})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_complete:
                if (mCompleteListener != null) {
                    int[] ids = null;
                    String[] parmas = null;
                    switch (mType) {
                        case 1:
                            ids = new int[]{mWheelLeft.getSelectItem()};
                            parmas = new String[]{mWheelLeft.getSelectText()};
                            break;
                        case 2:
                            ids = new int[]{mWheelLeft.getSelectItem(), mWheelCenter.getSelectItem(), mWheelRight.getSelectItem()};
                            parmas = new String[]{mWheelLeft.getSelectText(), mWheelCenter.getSelectText(), mWheelRight.getSelectText()};
                            break;
                        case 3:
                            if (areaList != null && areaList.size() > 0) {
                                ids = new int[]{mWheelCenter.getSelectItem()};
                                parmas = new String[]{areaList.get(ids[0]).id};
                            } else {
                                ids = new int[]{mWheelLeft.getSelectItem()};
                                parmas = new String[]{provinceList.get(ids[0]).id};
                            }
                            break;
                        case 4:
                            ids = new int[]{mWheelLeft.getSelectItem()};
                            parmas = new String[]{mWheelLeft.getSelectText()};
                            break;
                        case 5:
                            ids = new int[]{industryIdList.get(mWheelLeft.getSelectItem())};
                            parmas = new String[]{mWheelLeft.getSelectText()};
                            break;
                        case 6:
                            ids = new int[]{mWheelLeft.getSelectItem()};
                            parmas = new String[]{mWheelLeft.getSelectText()};
                            break;
                    }

                    mCompleteListener.completeSelect(ids, parmas);
                }
                exit();
                break;
            case R.id.tv_cancel:
                exit();
                break;
            case R.id.rl_wheel:
                exit();
                break;
        }
    }

    public void setSelectedCompleteListener(SelectedCompleteListener completeListener) {
        mCompleteListener = completeListener;
    }

    public void initSexData(int selectSex) {
        mWheelLeft.setVisibility(View.VISIBLE);
        mWheelCenter.setVisibility(View.GONE);
        mWheelRight.setVisibility(View.GONE);
        String[] sex = mActivity.getResources().getStringArray(R.array.sex_types);
        mWheelLeft.setData(Arrays.asList(sex));
        setSelectSex(selectSex);
    }

    public void setSelectSex(int selectSex) {
        if (mType == 1) {
            if (selectSex > 0) {
                selectSex = selectSex - 1;
            }
            mWheelLeft.setSelectItem(selectSex);
            mWheelLeft.build();
        }
    }

    public void initInvestmentBudget(int selectIndex) {
        mWheelLeft.setVisibility(View.VISIBLE);
        mWheelCenter.setVisibility(View.GONE);
        mWheelRight.setVisibility(View.GONE);
        String[] investmentBudget = mActivity.getResources().getStringArray(R.array.investment_budget);
        mWheelLeft.setData(Arrays.asList(investmentBudget));
        setSelectInvestmentBudget(selectIndex);
    }

    public void setSelectInvestmentBudget(int selectIndex) {
        if (mType == 6) {
            mWheelLeft.setSelectItem(selectIndex);
            mWheelLeft.build();
        }
    }

    private int thisYear;
    private int thisMonth;
    private int thisDay;

    public void initAgeData(int year, int month, int day) {
        mWheelLeft.setVisibility(View.VISIBLE);
        mWheelCenter.setVisibility(View.VISIBLE);
        mWheelRight.setVisibility(View.VISIBLE);

        calendar = Calendar.getInstance();

        thisYear = calendar.get(Calendar.YEAR);
        thisMonth = calendar.get(Calendar.MONTH) + 1;
        thisDay = calendar.get(Calendar.DAY_OF_MONTH);

        Logger.e("当前日期：" + thisYear + " 年 " + thisMonth + " 月 " + thisDay + " 日");

        List<String> years = new ArrayList<>();
        for (int i = 1950; i < thisYear + 1; i++) {
            years.add(String.valueOf(i));
        }

        mWheelLeft.setData(years);

        mWheelLeft.setOnWheelViewSelectListener(new WheelView.OnWheelViewSelectListener() {
            @Override
            public void onWheelViewSelect(int postion, String s) {
                int year = Integer.valueOf(s);
                int month = calendar.get(Calendar.MONTH) + 1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);

                Logger.e("Year WheelChange:" + year + " " + month + " " + day);

                setSelectAge(year, month , day);
            }
        });

        mWheelCenter.setOnWheelViewSelectListener(new WheelView.OnWheelViewSelectListener() {
            @Override
            public void onWheelViewSelect(int i, String s) {
                int year = calendar.get(Calendar.YEAR);
                int month = Integer.valueOf(s);
                int day = calendar.get(Calendar.DAY_OF_MONTH);

                Logger.e("Month WheelChange:" + year + " " + month + " " + day);

                setSelectAge(year, month, day);
            }
        });

        mWheelRight.setOnWheelViewSelectListener(new WheelView.OnWheelViewSelectListener() {
            @Override
            public void onWheelViewSelect(int i, String s) {
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1;
                int day = Integer.valueOf(s);

                Logger.e("Day WheelChange:" + year + " " + month + " " + day);

                calendar.set(year, month - 1, day);
            }
        });

        if (year == 0) {
            year = thisYear;
            month = thisMonth;
            day = thisDay;
        } else if (month == 0) {
            month = thisMonth;
            day = thisDay;
        } else if (day == 0) {
            day = thisDay;
        }

        setSelectAge(year, month, day);
    }

    public void setSelectAge(int year, int month, int day) {
        if (mType == 2) {

            int monthOfYeay = 12;
            if (year >= thisYear) {
                monthOfYeay = thisMonth;
                if (month > monthOfYeay) {
                    month = 1;
                }
            }

            List<String> months = new ArrayList<>();
            for (int i = 0; i < monthOfYeay; i++) {
                months.add(String.valueOf(i + 1));
            }

            mWheelCenter.setData(months);

            List<String> days = getDayOfMonth(year, month, day);

            mWheelRight.setData(days);

            mWheelLeft.setSelectText(String.valueOf(year));
            mWheelCenter.setSelectText(String.valueOf(month));
            mWheelRight.setSelectText(String.valueOf(day));

            mWheelLeft.build();
            mWheelCenter.build();
            mWheelRight.build();
        }
    }

    private List<String> getDayOfMonth(int year, int month, int day) {
        calendar.set(year, month, 0); //输入类型为int类型

        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        if (year >= thisYear && month >= thisMonth) {
            dayOfMonth = thisDay;
        }

        if (dayOfMonth < day) {
            day = 1;
        }

        calendar.set(year, month - 1, day);

        List<String> days = new ArrayList<>();
        for (int i = 1; i < dayOfMonth + 1; i++) {
            days.add(String.valueOf(i));
        }
        return days;
    }

    public void initAreaData(String areaId) {
        mWheelLeft.setVisibility(View.VISIBLE);
        mWheelCenter.setVisibility(View.VISIBLE);
        mWheelRight.setVisibility(View.GONE);
        provinceList = DbManager.getInstance().query(QueryBuilder.create(DistrictInfo.class).where("parentId = ?", "0"));
        List<String> provinces = new ArrayList<>();
        for (DistrictInfo provinceInfo : provinceList) {
            provinces.add(provinceInfo.name);
        }
        mWheelLeft.setData(provinces);

        mWheelLeft.setOnWheelViewSelectListener(new WheelView.OnWheelViewSelectListener() {
            @Override
            public void onWheelViewSelect(int i, String s) {
                getAreaOfProvince(provinceList.get(i).id, "");
            }
        });

        setSelectArea(areaId);
    }

    public void setSelectArea(String areaId) {
        if (mType == 3) {
            String provinceId;
            if (!TextUtils.isEmpty(areaId)) {
                DistrictInfo areaInfo = DbManager.getInstance().queryById(areaId, DistrictInfo.class);
                if (areaInfo != null) {
                    if (areaInfo.parentId.equals("0")) {
                        provinceId = areaInfo.id;
                        mWheelLeft.setSelectText(areaInfo.name);
                    } else {
                        DistrictInfo provinceInfo = DbManager.getInstance().queryById(areaInfo.parentId, DistrictInfo.class);
                        mWheelLeft.setSelectText(provinceInfo.name);
                        provinceId = provinceInfo.id;
                    }
                } else {
                    provinceId = provinceList.get(0).id;
                }
            } else {
                provinceId = provinceList.get(0).id;
                areaId = "";
            }

            getAreaOfProvince(provinceId, areaId);
            mWheelLeft.build();
        }
    }

    private void getAreaOfProvince(String provinceId, String areaId) {
        areaList = DbManager.getInstance().query(QueryBuilder.create(DistrictInfo.class).where("parentId= ?", provinceId));
        if (areaList != null && areaList.size() > 0) {
            mWheelCenter.setVisibility(View.VISIBLE);
            int selectArea = 0;
            List<String> areas = new ArrayList<>();
            for (int i = 0; i < areaList.size(); i++) {
                DistrictInfo areaInfo = areaList.get(i);
                areas.add(areaInfo.name);
                if (areaInfo.id.equals(areaId)) {
                    selectArea = i;
                }
            }
            mWheelCenter.setData(areas);
            mWheelCenter.setSelectItem(selectArea);
            mWheelCenter.build();
        } else {
            mWheelCenter.setVisibility(View.INVISIBLE);
        }
    }

    public void initPeriodData(int selectPeriod) {
        mWheelLeft.setVisibility(View.VISIBLE);
        mWheelCenter.setVisibility(View.GONE);
        mWheelRight.setVisibility(View.GONE);
        String[] guideStates = mActivity.getResources().getStringArray(R.array.period_types);
        mWheelLeft.setData(Arrays.asList(guideStates));
        setSelectPeriod(selectPeriod);
    }

    public void setSelectPeriod(int selectPeriod) {
        if (mType == 4) {
            mWheelLeft.setSelectItem(selectPeriod);
            mWheelLeft.build();
        }
    }

    public void initIndustryData(int selectIndustry) {
        mWheelLeft.setVisibility(View.VISIBLE);
        mWheelCenter.setVisibility(View.GONE);
        mWheelRight.setVisibility(View.GONE);

        industryIdList = new ArrayList<>();
        List<String> IndustryString = new ArrayList<>();

        List<InterestIndustryInfo> industryList = DbManager.getInstance().query(new QueryBuilder<InterestIndustryInfo>(InterestIndustryInfo.class).appendOrderAscBy("sort"));
        for (int i = 0; i < industryList.size(); i++) {
            InterestIndustryInfo industryInfo = industryList.get(i);
            if (!industryInfo.name.equals("创业交流")) {
                industryIdList.add(industryInfo.categoryId);
                IndustryString.add(industryInfo.name);
            }
        }

        mWheelLeft.setData(IndustryString);

        setSelectIndustry(selectIndustry);
    }

    public void setSelectIndustry(int selectIndustry) {
        if (mType == 5) {
            int selectIndex = 0;
            for (int i = 0; i < industryIdList.size(); i++) {
                if (selectIndustry == industryIdList.get(i)) {
                    selectIndex = i;
                }
            }
            mWheelLeft.setSelectItem(selectIndex);
            mWheelLeft.build();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        setWindowHeight();
    }

    private void setWindowHeight() {
        WindowManager.LayoutParams p = getDialog().getWindow().getAttributes();
        p.width = RelativeLayout.LayoutParams.MATCH_PARENT;
        p.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
        getDialog().getWindow().setAttributes(p);
    }

    public interface SelectedCompleteListener {
        void completeSelect(int[] i, String[] params);
    }

}